/**
 * 
 */
package base.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * 文件写入
 * @author liuboen
 * 
 * since:2012-6-8
 * version:1.0.0
 */
public class FileWriterHandle {

	/**
	 * 使用默认编码输出字符文件
	 * @param text
	 * @param pathname
	 * @throws IOException
	 */
	public static void writeTextFile(String text, String pathname)throws IOException {
		//获取写入字符文件的便捷类
		FileWriter fileWriter = new FileWriter(pathname);
		//缓冲输出,防止每个字符进行字节转换并迅速写入文件,提高性能
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
		bufferedWriter.write(text);
		
		//close 前必须flush
		bufferedWriter.flush();
		bufferedWriter.close();
		fileWriter.close();

	}
	/**
	 * 使用指定编码输出字符文件
	 * @param text
	 * @param pathname
	 * @param charsetName
	 * @throws IOException
	 */
	public static void writeTextFile(String text, String pathname,String charsetName)throws IOException {
		//	指定编码和缓冲区大小这些值，可以先在 FileOutputStream 上构造一个 OutputStreamWriter。 
		FileOutputStream fileOutputStream = new FileOutputStream(new File(pathname));
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream , charsetName);
		//	缓冲输出,防止每个字符进行字节转换并迅速写入文件,提高性能
		BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
		bufferedWriter.write(text);
		
		//close 前必须flush
		bufferedWriter.flush();
		bufferedWriter.close();
		outputStreamWriter.close();
		fileOutputStream.close();
		
	}
	
	public static void main (String []a){
		try {
			FileWriterHandle.writeTextFile("测试A A A A a啊啊啊阿 ", "D:/test.txt");
			FileWriterHandle.writeTextFile("测试A A A A a啊啊啊阿11123213 ", "D:/test.txt" ,"GBK");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
